<template>
  <div>
    <div style="text-align: left; margin-bottom: 5px; display: flex">
      <el-button size="mini" type="primary" @click="toAdd">
        添加
      </el-button>
      <div style="margin-left: 10px">
        商品名
        <el-input v-model="searchParams.goodsName" @input="filterGoods" clearable style="width: 150px"
                  size="mini"></el-input>
      </div>
      <div style="margin-left: 10px">
        商品种类
        <el-select v-model="searchParams.goodsCategoryName" size="mini" placeholder="请选择商品种类" clearable
                   @change="filterGoods()">
          <el-option v-for="(item,index) in goodsCategoryList" :key="index" :label="item.name"
                     :value="item.name"></el-option>
        </el-select>
      </div>
    </div>

    <!--增加或更新商品-->
    <el-dialog :title=formTitle :visible.sync="flagShowGoodsForm">
      <el-form :model="formData" label-width="150px" style="text-align:left">
        <el-form-item label="商品名称" prop="name" required>
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="商品种类" required>
          <el-select v-model="formData.goodsCategoryId" placeholder="请选择商品种类" style="float: left">
            <el-option v-for="(item,index) in goodsCategoryList" :key="index" :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="显示顺序" prop="displayOrder">
          <el-input-number v-model="formData.displayOrder" type="number"></el-input-number>
        </el-form-item>
        <el-form-item label="默认价格(单位: 分)" prop="price" required>
          <el-input-number v-model="formData.price" type="number" placeholder="必须大于0"></el-input-number>
        </el-form-item>
        <el-form-item label="默认库存" prop="price" required>
          <el-input-number v-model="formData.count" type="number" placeholder="必须大于0"></el-input-number>
        </el-form-item>
        <el-form-item label="商品图片" prop="image" required>
          <el-input v-model="formData.image" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="formData.description" maxlength="100"
                    placeholder="商品描述, 最多100字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="confirmSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 商品列表-->
    <el-table
        :data="goodsList.slice((searchParams.pageNo-1)*searchParams.pageSize, searchParams.pageNo*searchParams.pageSize)"
        :row-key="row =>{ return row.id; }"
        :expand-row-keys="expands"
        @row-click="clickRow"
        :default-sort="{prop: 'displayOrder'}">

      <!--行展开后显示-商品的属性列表-->
      <el-table-column type="expand" @click="()=>{alert(1)}">
        <GoodsProperty :curGoods="curGoods" @updateGoodsPropertyList="updateGoodsPropertyList"
                       style="box-shadow:0 0 10px gray; padding:10px"></GoodsProperty>
      </el-table-column>

      <el-table-column label="id" prop="id" sortable></el-table-column>
      <el-table-column label="商品名称" prop="name" sortable></el-table-column>
      <el-table-column label="商品种类" prop="goodsCategoryName" sortable></el-table-column>
      <el-table-column label="显示顺序" prop="displayOrder" sortable></el-table-column>
      <el-table-column label="默认价格">
        <template slot-scope="scope">
          {{ '￥' + scope.row.price / 100 }}
        </template>
      </el-table-column>
      <el-table-column label="默认库存" prop="count"></el-table-column>

      <!--上传商品图片-->
      <el-table-column label="商品图片">
        <template slot-scope="scope">
          <el-upload
              :action="getUploadGoodsImgUrl(scope.row.id)"
              :before-upload="beforeAvatarUpload"
              :on-success="(result)=>{handleAvatarSuccess(result, scope.row.id)}"
              :on-error="handleAvatarFail">
            <img v-if="scope.row.image" :src="scope.row.image" style="width: 50px; height: 50px" alt=""/>
            <div v-else style="border:1px solid lightgray; color: lightgray; width: 50px; height: 50px">+上传图片</div>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="商品描述"></el-table-column>

      <el-table-column label="是否上架">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status === 1" @change="updateGoodsStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="130">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="toEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="mini" @click="toDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-row style="float: right">
      <el-pagination
          @current-change="changePageNo"
          @size-change="changePageSize"
          :current-page.sync="searchParams.pageNo"
          :page-sizes="[1, 5, 10, 50, 250]"
          :page-size.sync="searchParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-row>
  </div>
</template>

<script>
import * as goodsAdminApi from "../../api/goodsAdminApi.js";
import * as goodsCategoryAdminApi from "../../api/goodsCategoryAdminApi.js";
import config from "../../../config"
import GoodsProperty from "./goodsProperty"

export default {
  name: "goodsAdminComponent",
  components: {GoodsProperty},
  data() {

    return {
      // 查询参数
      searchParams: {
        goodsName: "",
        goodsCategoryName: "",
        pageNo: 1,
        pageSize: 5,
      },
      goodsCategoryList: [], // 商品类别列表
      total: 0,
      allGoods: [],
      goodsList: [],
      flagShowGoodsForm: false,
      formTitle: '添加',
      formData: {},
      expands: [], // 展开的行
      curGoods: {}, // 当前商品
      flagShowPropertyOptionDisableList: false,
      disableList: [], // 属性禁用列表
    }

  },
  mounted() {
    goodsCategoryAdminApi.getGoodsCategoryList({
      success: res => {
        this.goodsCategoryList = res.data
      }
    })
    this.getGoodsList();
  },
  methods: {
    // 上传商品图片的url
    getUploadGoodsImgUrl(goodsId) {
      return config.baseUrl + "/goods/uploadGoodsImg/" + goodsId + "?token=" + window.localStorage.getItem('token')
    },
    // 获取商品列表
    getGoodsList() {
      goodsAdminApi.getGoodsList({
        success: res => {
          this.allGoods = res.data
          this.goodsList = res.data
          this.filterGoods()
        }
      })
    },
    filterGoods() {
      this.goodsList = this.allGoods.filter(goods => {
        return (this.searchParams.goodsName === "" || goods.name.indexOf(this.searchParams.goodsName) >= 0)
            && (this.searchParams.goodsCategoryName === "" || goods.goodsCategoryName.indexOf(this.searchParams.goodsCategoryName) >= 0)
      })
      this.total = this.goodsList.length
    },
    // 切换页数
    changePageNo(pageNo) {
      this.searchParams.pageNo = pageNo;
      this.filterGoods()
    },
    // 改变页面大小
    changePageSize(pageSize) {
      this.searchParams.pageSize = pageSize;
      this.filterGoods()
    },
    // 重置商品数据表单
    resetForm() {
      this.formData = {
        goodsCategoryId: '',
        name: '',
        displayOrder: 0,
        price: 0,
        count: 0,
        description: '',
      }
    },
    // 增加商品
    toAdd() {
      this.resetForm()
      this.flagShowGoodsForm = true
      this.formTitle = '添加'
    },
    // 删除商品
    toDelete(goods) {
      this.$confirm(`是否删除id为${goods.id}的商品${goods.name}`).then(() => {
        goodsAdminApi.deleteGoods({
          goodsId: goods.id,
          success: () => {
            this.getGoodsList()
          }
        })
      }).catch(() => {
      })
    },
    // 编辑商品
    toEdit(selectedGoodsAdmin) {
      // 深拷贝一个对象 不然在表格显示的数据会受到印象
      this.formData = JSON.parse(JSON.stringify(selectedGoodsAdmin));
      this.flagShowGoodsForm = true
      this.formTitle = '更新'
    },
    // 提交更新商品的表单
    confirmSubmit() {
      let that = this
      let errMsg = ""
      if (!that.formData.name)
        errMsg = "请输入商品名称"
      else if (!that.formData.goodsCategoryId)
        errMsg = "请选择商品种类"
      else if (that.formData.price <= 0)
        errMsg = "请设置商品默认价格(必须大于0)"
      if (errMsg !== "") {
        this.$message.error(errMsg)
        return
      }

      this.flagShowGoodsForm = false;
      if (this.formTitle.startsWith('添加')) {
        goodsAdminApi.addGoods({
          data: this.formData,
          success: () => {
            this.getGoodsList()
          }
        })
      } else if (this.formTitle.startsWith('更新')) {
        goodsAdminApi.updateGoods({
          data: this.formData,
          success: () => {
            this.getGoodsList()
          }
        })
      }
    },
    // 上架或下架商品
    updateGoodsStatus(goods) {
      let newStatus = (goods.status === 1 ? 2 : 1)
      goodsAdminApi.updateGoods({
        data: {
          ...goods,
          status: newStatus,
        },
        success: () => {
          goods.status = newStatus
          this.$notify.success(newStatus === 1 ? "上架成功" : "已下架")
        }
      })
    },
    // 上传商品图片成功回调
    handleAvatarSuccess(result, goodsId) {
      console.log(JSON.stringify(result))
      if (result.code >= 0 && result.code < 30000) {
        for (let i = 0; i < this.goodsList.length; i++)
          if (this.goodsList[i].id === goodsId)
            this.goodsList[i].image = result.data
      } else {
        this.$message.error("上传失败: " + result.msg)
      }
    },
    handleAvatarFail(err) {
      this.$message.error('上传失败: ' + JSON.stringify(err))
    },
    // 上传图片前的处理操作
    beforeAvatarUpload(file) {
      const isPicture = (file.type === 'image/jpeg');
      const isLess1MB = file.size / 1024 / 1024 < 1;
      if (!isPicture) {
        this.$message.error('请上传图片格式的文件');
      }
      if (!isLess1MB) {
        this.$message.error('头像图片大小不能超过1MB!');
      }
      return isPicture && isLess1MB;
    },
    // 点击表格中的某一行的回调, 控制只有一行被展开 {row,column,event}
    clickRow(rowData, column) {
      if (column.label === '是否上架' || column.label === '操作')
        return
      let index = this.expands.findIndex(e => {
        return e === rowData.id
      })
      if (index >= 0) { // 重复点击当前行，直接收起全部
        this.expands = []
      } else {
        this.expands = [rowData.id]
      }

      this.curGoods = rowData
    },
    // 子组件更新完商品属性列表后的通知
    updateGoodsPropertyList() {
      this.getGoodsList()
      this.expands = []
    }

  }
}
</script>
